#include <cserver/restapi.h>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/uuid/sha1.hpp>
#include <boost/log/trivial.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <pqxx/transaction.hxx>

#include <sstream>

namespace csrv{ namespace webcmd{
	static const char* K_this_command= "api/v1/hydrant/data";

	void hydrant_data(Request& req, pqxx::connection& dbconn, SessionContext& , const std::string& /*cmd*/ ){
		auto query = parseQuery(req.getParam("QUERY_STRING"));
		auto& callback = query["callback"];
		auto& pattern = query["pattern"];
		pattern.insert(pattern.begin(), '%');
		pattern.push_back('%');
		auto& euid = query["euid"];
		auto& from = query["fdate"];
		auto& to = query["tdate"];
		bool for_history = euid.empty();

		unsigned int offset=0;
		unsigned int limit=0;
		auto& from_s = query["from"];
		auto& count_s = query["count"];

		if (for_history){
			offset = from_s.empty() ? unsigned(0): boost::lexical_cast<unsigned>(from_s);
			limit = count_s.empty() ? unsigned(2000): boost::lexical_cast<unsigned>(count_s);
			limit = std::min(limit, unsigned(2000));
			limit = std::max(limit, unsigned(1));
		}

		StreamGroup sg(req);
		auto& fout = sg.fout;
		if (!euid.empty() &&( from.empty() || to.empty())){
			response_error(sg.fout, 400, "ErrParameter", "BadParameter", req);
			return;
		}

		response_header(sg.fout, 200);
		if (!callback.empty()) sg.fout << callback << "(";

		pqxx::work w(dbconn);
#if 1
		fout << boost::format(R"({"func":"hydrant/data",
"args":{},
"ret":{"success":true, "message":"",
"total":%1%,
"value":)") %( for_history ? TotalCount(w, "get_hydrant_data_history_total")(pattern).result() : TotalCount(w, "get_hydrant_data_total")(euid)(from)(to).result());
#endif
		auto result = (for_history ? w.prepared("get_hydrant_data_history")(pattern)(limit)(offset).exec() : w.prepared("get_hydrant_data")(euid)(from)(to).exec());
		fout << result2json(result, for_history? 4:1);
		fout << "}}";
		if (!callback.empty()) sg.fout << ")";
	}
}

static CommandAddHelper k_registerHandler("GET", webcmd::K_this_command, &webcmd::hydrant_data);
}


